/**
 * author:Administrator
 * date:2016/3/15
 * desc: output format
 * 格式输出
 */

'use strict';

class FormatOutput {
  constructor(code, msg, payload) {
    this.code = code;
    if (msg) this.msg = msg;
    if (payload) this.payload = payload;
  }

  isOk() {
    return this.code == 0;
  }

  getmsg() {
    return this.msg;
  }

  getPayload() {
    return this.payload;
  }

  static fromJson(json) {
    if (typeof json === 'string') json = JSON.parse(json);
    return new FormatOutput(json.code, json.msg, json.payload);
  }

  static payloadOrError(payload, err) {
    if (payload) {
      if (payload instanceof FormatOutput)
        return payload;
      else
        return new FormatOutput(0, null, payload);
    }
    if (err instanceof FormatOutput)
      return err;
    else
      return new FormatOutput(err.code, err.msg, null);
  }

  toJson() {
    let json = {
      code: this.code,
      msg: this.msg,
      payload: this.payload
    };
    return Object.freeze(json);
  }
}

module.exports = FormatOutput;
